package org.chencc98.mycommon.mybatis;

import java.io.IOException;
import java.io.InputStream;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.chencc98.mycommon.util.MyLoggerUtil;
import org.chencc98.mycommon.util.ParamUtil;



/** sigleton mode for mybatis factory
 * 
 * @author chenxianpeng
 *
 */
public class MybatisXmlFactory {
	private static MyLoggerUtil logger = MyLoggerUtil.getLogger(MybatisXmlFactory.class);
	private static MybatisXmlFactory factory = null;
	private static String configXml = "mybatis_config.xml";

	private SqlSessionFactory sessionFactory = null;
	
	private MybatisXmlFactory() {
		// TODO Auto-generated constructor stub
		String mybatisConfig = configXml;
		InputStream is = MybatisXmlFactory.class.getClassLoader().getResourceAsStream(mybatisConfig);
		logger.debug("InputStream created " + is);
		sessionFactory = new SqlSessionFactoryBuilder().build(is);
		logger.debug("sessionFactory created");
		try {
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			//ignore
		}
	}
	
	public static synchronized String getConfigXml() {
		return configXml;
	}

	public static synchronized void setConfigXml(String configXml) {
		ParamUtil.checkNull(configXml, "mybatis config xml");
		if (factory == null) {
			MybatisXmlFactory.configXml = configXml;
		} else {
			logger.warn("initialiazed, so skip...");
		}
		
	}
	
	public static synchronized boolean isInit() {
		if (factory == null) {
			return false;
		}
		return true;
	}

	public static MybatisXmlFactory getInstance() {
		if (factory == null) {
			synchronized(MybatisXmlFactory.class) {
				if (factory == null) {
					factory = new MybatisXmlFactory();
				}
			}
		}
		return factory;
	}
	
	
	
	
	public SqlSession openSession() {
		return sessionFactory.openSession();
	}
	
	

}
